package com.song.controller.school;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.policy.PictureRenderPolicy;
import com.deepoove.poi.util.PoitlIOUtils;
import com.song.api.Insert;
import com.song.api.Update;
import com.song.enums.GenderEnum;
import com.song.model.ResultEntity;
import com.song.util.excel.EasyPoiUtil;
import com.song.util.excel.PoiUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.entity.school.Student;
import com.song.service.school.StudentService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
* <p>
    * 学生信息 控制器
    * </p>
*
* @author song
* @since 2024-11-29
*/
@Api(tags = {"学生信息 控制器"})
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    StudentService studentService;

    /**
    * 分页查询数据
    *
    * @author song
    * @Date 2024-11-29
    */
    @ApiOperation(value = "按条件分页检索学生信息",notes = "按条件分页检索学生信息")
    @GetMapping(value = "/pageList")
    public ResultEntity<Page<Student>> pageList(
        @Validated Student student,
        @ApiParam(value = "页码", defaultValue = "1")
        @RequestParam(defaultValue = "1") int pageNum,
        @ApiParam(value = "分页大小", defaultValue = "10")
        @RequestParam(defaultValue = "10") int pageSize
    ) {
        Page<Student> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        if(ObjectUtils.isNotEmpty(student.getId())){
            lambda.eq(Student::getId,student.getId());
        }
        if(ObjectUtils.isNotEmpty(student.getXm())){
            lambda.eq(Student::getXm,student.getXm());
        }
        if(ObjectUtils.isNotEmpty(student.getXb())){
            lambda.eq(Student::getXb,student.getXb());
        }
        if(ObjectUtils.isNotEmpty(student.getXh())){
            lambda.eq(Student::getXh,student.getXh());
        }
        if(ObjectUtils.isNotEmpty(student.getSfzh())){
            lambda.eq(Student::getSfzh,student.getSfzh());
        }
        if(ObjectUtils.isNotEmpty(student.getCsrq())){
            lambda.eq(Student::getCsrq,student.getCsrq());
        }
        if(ObjectUtils.isNotEmpty(student.getCjsj())){
            lambda.eq(Student::getCjsj,student.getCjsj());
        }
        if(ObjectUtils.isNotEmpty(student.getGxsj())){
            lambda.eq(Student::getGxsj,student.getGxsj());
        }
        return ResultEntity.success(studentService.page(page,lambda));
    }

    /**
    * 查询数据List
    *
    * @author song
    * @Date 2024-11-29
    */
    @ApiOperation(value = "查询全部学生信息",notes = "查询全部学生信息")
    @GetMapping(value = "/list")
    public ResultEntity<List<Student>> list() {
        List<Student> studentList = studentService.list();
        return ResultEntity.success(studentList);
    }

    /**
    * 学生信息新增
    *
    * @author song
    * @Date 2024-11-29
    */
    @ApiOperation(value = "新增学生信息",notes = "新增学生信息")
    @PostMapping(value = "/add")
    public ResultEntity add(@Validated(Insert.class) @RequestBody Student student) {
        studentService.save(student);
        return ResultEntity.success();
    }

    /**
    * 学生信息修改
    *
    * @author song
    * @Date 2024-11-29
    */
    @ApiOperation(value = "修改学生信息",notes = "修改学生信息")
    @PostMapping(value = "/update")
    public ResultEntity edit(@Validated(Update.class) @RequestBody Student student) {
        studentService.updateById(student);
        return ResultEntity.success();
    }

    /**
    * 删除学生信息
    *
    * @author song
    * @Date 2024-11-29
    */
    @ApiOperation(value = "按id删除学生信息",notes = "按id删除学生信息")
    @PostMapping(value = "/delete")
    public ResultEntity delete(@RequestParam Serializable id) {
        studentService.removeById(id);
        return ResultEntity.success();
    }


    /**
    * 根据id查询学生信息
    *
    * @author song
    * @Date 2024-11-29
    */
    @ApiOperation(value = "根据id查询学生信息",notes = "根据id查询修改学生信息")
    @GetMapping(value = "/detail")
    public ResultEntity<Student> detail(@RequestParam Serializable id) {
        Student student = studentService.getById(id);
        return ResultEntity.success(student);
    }

    @ApiOperation(value = "导入学生信息(含图片)",notes = "导入学生信息(含图片)")
    @PostMapping("/importList")
    public ResultEntity importList(MultipartFile file){
        List<Student> studentList = studentService.importList(file);
        return ResultEntity.success(studentList);
    }

    @ApiOperation(value = "导出学生信息(含图片)",notes = "导出学生信息(含图片)", produces = "application/octet-stream")
    @GetMapping("/exportList")
    public void exportList(HttpServletResponse response){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        XSSFDrawing drawing = sheet.createDrawingPatriarch();
        List<Student> studentList = studentService.list();
        List<String> headers = Arrays.asList("姓名", "性别", "学号", "身份证号", "学籍照", "头像");
        XSSFRow headerRow = sheet.createRow(0);
        CellStyle headerStyle = PoiUtil.headerStyle(workbook);
        for (int i = 0; i < headers.size(); i++) {
            XSSFCell cell = headerRow.createCell(i);
            cell.setCellValue(headers.get(i));
            cell.setCellStyle(headerStyle);
        }
        int rowIndex = 1;
        CellStyle commonStyle = PoiUtil.commonStyle(workbook);
        for (Student student : studentList) {
            XSSFRow row = sheet.createRow(rowIndex);
            for (int i = 0; i < headers.size(); i++) {
                XSSFCell cell = row.createCell(i);
                cell.setCellStyle(commonStyle);
                switch (headers.get(i)){
                    case "姓名":
                        cell.setCellValue(student.getXm());
                        break;
                    case "性别":
                        cell.setCellValue(GenderEnum.getGenderDesc(student.getXb()));
                        break;
                    case "学号":
                        cell.setCellValue(student.getXh());
                        break;
                    case "身份证号":
                        cell.setCellValue(student.getSfzh());
                        break;
                    case "学籍照":
                        if (StringUtils.isNotBlank(student.getXjz())){
                            int pictureIndex = workbook.addPicture(Base64.getDecoder().decode(student.getXjz()), Workbook.PICTURE_TYPE_JPEG);
                            XSSFCreationHelper helper = workbook.getCreationHelper();
                            XSSFClientAnchor anchor = helper.createClientAnchor();
                            anchor.setCol1(cell.getColumnIndex());
                            anchor.setRow1(row.getRowNum());
                            XSSFPicture picture = drawing.createPicture(anchor, pictureIndex);
                            picture.resize();
                        }
                        break;
                    case "头像":
                        if (StringUtils.isNotBlank(student.getTx())){
                            int pictureIndex = workbook.addPicture(Base64.getDecoder().decode(student.getTx()), Workbook.PICTURE_TYPE_JPEG);
                            XSSFCreationHelper helper = workbook.getCreationHelper();
                            XSSFClientAnchor anchor = helper.createClientAnchor();
                            anchor.setCol1(cell.getColumnIndex());
                            anchor.setRow1(row.getRowNum());
                            XSSFPicture picture = drawing.createPicture(anchor, pictureIndex);
                            picture.resize();
                        }
                        break;
                }
            }
            rowIndex++;
        }
        try {
            EasyPoiUtil.downLoadExcel("学生信息", response, workbook);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @ApiOperation(value = "导出文档",notes = "导出文档", produces = "application/octet-stream")
    @GetMapping("/exportWord")
    public void exportWord(HttpServletResponse response) throws Exception {
        String path = "D:\\song\\gitee\\spring-boot-jackson\\src\\main\\resources\\download\\word\\导出模板.docx";
        List<Student> list = studentService.list();
        for (Student student : list){
            if (ObjectUtils.isNotEmpty(student.getXjz())){
                PictureRenderData pictureRenderData = new PictureRenderData(80, 60, PictureType.JPEG, Base64.getDecoder().decode(student.getXjz()));
                student.setXjzData(pictureRenderData);
            }
        }
        //设置动态表格
        Map<String, Object> map = new HashMap<>();
        map.put("studentList", list);
        LoopRowTableRenderPolicy loopRowTableRenderPolicy = new LoopRowTableRenderPolicy();
        Configure configure = Configure.builder()
                .bind("studentList", loopRowTableRenderPolicy)
                .build();
        //设置图片，否则导出是一段字符串
        configure.customPolicy("xjzData", new PictureRenderPolicy());
        XWPFTemplate xwpfTemplate = XWPFTemplate.compile(path, configure).render(map);
        try {
            EasyPoiUtil.downloadWord("导出模板.docx", response,  xwpfTemplate);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
}